package ch7.ex14;

import static ch7.print.Print.*;

class NonSharedMember{
	public NonSharedMember(String id) {
		println("Non shared member constructor " + id);
	}
}

class SharedMember{
	private int refcount;
	
	public void addRef(){
		println("Number of references " + ++refcount);
	}
	protected void dispose(){
		if(--refcount == 0)
			println("Disposing " + this);
	}
	public SharedMember(){
		println("SharedMember constructor");
	}
	public String toString(){
		return "SharedMember";
	}
}

class Rodent{
	private SharedMember mm;
	
	NonSharedMember m = new NonSharedMember("r1"),
		   			p = new NonSharedMember("r2");
	
	public Rodent(SharedMember sm) {
		println("Rodent constructor");
		mm = sm;
		mm.addRef();
	}
	public void hop(){
		println("Rodent hopping");
	}
	public void scurry(){
		println("Rodent scurring");
	}
	public void reproduce(){
		println("Making more Rodents");
	}
	protected void dispose(){
		println("Disposing " + this);
		mm.dispose();
	}
	public String toString(){
		return "Rodent";
	}
}

class Mouse extends Rodent{
	private SharedMember mm;
	
	NonSharedMember m = new NonSharedMember("m1"),
	       			p = new NonSharedMember("m2");
	
	public Mouse(SharedMember sm) {
		super(sm);
		println("Mouse constructor");
	}
	public void hop(){
		println("Mouse hopping");
	}
	public void scurry(){
		println("Mouse scurring");
	}
	public void reproduce(){
		println("Making more Mouses");
	}
	public String toString(){
		return "Mouse";
	}
}

class Gerbil extends Rodent{
	private SharedMember mm;
	
	NonSharedMember m = new NonSharedMember("g1"),
    	   			p = new NonSharedMember("g2");
	
	public Gerbil(SharedMember sm) {
		super(sm);
		println("Gerbil constructor");
	}
	public void hop(){
		println("Gerbil hopping");
	}
	public void scurry(){
		println("Gerbil scurring");
	}
	public void reproduce(){
		println("Making more Gerbils");
	}
	public String toString(){
		return "Gerbil";
	}
}

class Hamster extends Rodent{
	private SharedMember mm;
	
	NonSharedMember m = new NonSharedMember("h1"),
    	   			p = new NonSharedMember("h2");
	
	public Hamster(SharedMember sm) {
		super(sm);
		println("Hamster constructor");
	}
	public void hop(){
		println("Hamster hopping");
	}
	public void scurry(){
		println("Hamster scurring");
	}
	public void reproduce(){
		println("Making more Hamsters");
	}
	public String toString(){
		return "Hamster";
	}
} 
public class RodentInit {
	public static void main(String... args){
		SharedMember sm = new SharedMember();
		Rodent[] rodents = {
				new Hamster(sm),
				new Gerbil(sm),
				new Mouse(sm)
		};
		for(Rodent r:rodents)
			r.dispose();
	}
}
